/* 动态缓存数据，代理访问 */
import timeFormat from '@/uview-ui/libs/function/timeFormat'
import { BASE_URL } from '@/static/staticData'

/* 比赛数据 */
let competitions = []

import { getAllCompetition } from '@/api/competition.js'
export function getCompetitions() {
  if (competitions.length === 0) {
    return getAllCompetition()
      .then(res => {
        competitions = res.pageData
        return competitions
      })
  }

  return JSON.parse(JSON.stringify(competitions))
}
/**
 * 根据key val值查找比赛
 * @param {String} val
 * @param {String} key
 */
export function findCompetition(val, key = 'id') {
  return competitions.find(item => item[ key ] === val) || null
}

/* 课程数据 */
const courses = {}

import { getCourses } from '@/api/system.js'
export function getCoursesData(type) {
  if (!courses[ type ]) {
    return getCourses(type)
      .then(res => {
        courses[ type ] = res
        return courses[ type ]
      })
  }

  return JSON.parse(JSON.stringify(courses[ type ]))
}

/* 论坛标签 */
let forumTags = []

import { getDiscussionTags } from '@/api/forum.js'
export async function getForumTags() {
  if (forumTags.length === 0) {
    getDiscussionTags()
      .then(res => {
        forumTags = res
        console.log(res)
        return res
      })
  }
  return JSON.parse(JSON.stringify(forumTags))
}

/* 运行环境 */
let env = null

/**
 * 获取运行环境
 * @returns develop开发板 / trial体验版 / release正式版
 */
export function getEnv() {
  if (!env) {
    env = uni.getAccountInfoSync().miniProgram.envVersion
  }
  return {
    name: env,
    baseUrl: BASE_URL[ env ]
  }
}

/* 富文本页面跳转数据 */
let richText = { // 富文本阅读
  content: '', // 富文本内容
  name: '' // 顶部nav文字
}

/**
 * 设置跳转路径中富文本参数
 * @param {String} content
 * @param {String} name
 * @returns {boolean}
 */
export function setRichText(content, name = '阅读') {
  if (content) {
    richText = {
      content, name
    }
    return true
  }
  return false
}

/**
 * 获取跳转路径富文本参数
 * @returns {Object}
 */
export function getRichText() {
  return JSON.parse(JSON.stringify(richText))
}

/* md编辑器 */
let editContent = ''

/**
 * 获取并删除md内容
 * @param {Boolean} clear是否删除
 */
export function getEditContent(clear = false) {
  const temp = editContent

  if (clear) {
    editContent = null
  }
  return temp
}
/**
 * 设置edit内容
 */
export function setEditContent(content = null) {
  editContent = content
}

/* 用户搜索回调 */
let searchUserId = null
/**
 * 记录搜索的用户
 */

export function serSearchUser(id) {
  searchUserId = id
}
/**
 * 获取用户搜索id
 */
export function getSearchUser() {
  const temp = searchUserId

  searchUserId = null
  return temp
}
